

const wasmModuleRef: any = {};

const loadWasm = async () => {

    if (wasmModuleRef.value) {
        return wasmModuleRef.value;
    }

    let _resolve: any;
    let _reject: any;
    const p = new Promise((resolve, reject) => {
        _resolve = resolve;
        _reject = reject;
    });

    let script: any;

    try {



        // Create a script element to load the WASM JavaScript file
        script = document.createElement('script');
        script.src = `/Spire.Doc.Base.js`;
        script.onload = () => {
            try {

                // Access the Module and spiredoc from the global window object
                const { Module, spiredoc } = window;
                wasmModuleRef.value = (spiredoc);

                // Set the wasmModule state when the runtime is initialized
                Module.onRuntimeInitialized = () => {
                    _resolve({
                        Module, spiredoc
                    })
                };
            } catch (err) {
                _reject(err);
                // Log any errors that occur during loading
                console.error('Failed to load WASM module:', err);
            }
        };
        script.onerror = (err) => {
            console.error(err);
            _reject(err);
        };

        // Append the script to the document body
        document.body.appendChild(script);

    } catch (err) {
        console.error(err);
        _reject(err);
        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
    } finally {
        if (script) {
            document.body.removeChild(script);
        }
    }

    await p;
    return wasmModuleRef.value;
};


export const rtfArrayBufferToHtmlStr = async (ab: ArrayBuffer) => {

    const wasmModule = await loadWasm();

    try {

        if (wasmModule) {
            // Load font file
            // await wasmModule.FetchFileToVFS("ARIALUNI.TTF", "/Library/Fonts/", `/static/font/`);
            await wasmModule.FetchFileToVFS("SIMSUN.TTC", "/Library/Fonts/", `/static/font/`);

            // Load the Word file
            let inputFileName = "aaaaa.rtf";
            // await wasmModule.FetchFileToVFS(inputFileName, "", `/`);

            // const importFile = await importRtfFileToString();
            // inputFileName = importFile.name;
            // await wasmModule.FS.writeFile(inputFileName, (importFile.arrayBuffer));
            await wasmModule.FS.writeFile(inputFileName, (ab));

            // Create a new document object
            const document = wasmModule.Document.Create();
            // Load the Word file
            document.LoadFromFile(inputFileName);

            // Define output file name
            const outputFileName = "test.html";

            // Save to PDF
            document.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Html });

            // Clean up resources
            document.Dispose();


            // Read the saved file and convert to a Blob object
            const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

            var decoder = new TextDecoder("utf-8");
            const htmlStr = decoder.decode(modifiedFileArray);

            return htmlStr;
            // console.log({htmlStr});

            // outputRef.value.innerHTML=htmlStr;

            // const modifiedFile = new Blob([modifiedFileArray], { type: "text/html" });

            // // Set download properties
            // downloadName.value = outputFileName;
            // downloadUrl.value = URL.createObjectURL(modifiedFile);
        } else {
          console.error("Not Exist wasmModule!:", wasmModule);
        }

    } catch (error) {
        console.error("Error processing the document:", error);
    }

    return '';


};

export const rtfArrayBufferToDocx = async (ab: ArrayBuffer) => {

    const wasmModule = await loadWasm();

    try {

        if (wasmModule) {
            // Load font file
            // await wasmModule.FetchFileToVFS("ARIALUNI.TTF", "/Library/Fonts/", `/static/font/`);
            await wasmModule.FetchFileToVFS("SIMSUN.TTC", "/Library/Fonts/", `/static/font/`);

            // Load the Word file
            let inputFileName = "aaaaa.rtf";
            // await wasmModule.FetchFileToVFS(inputFileName, "", `/`);

            // const importFile = await importRtfFileToString();
            // inputFileName = importFile.name;
            // await wasmModule.FS.writeFile(inputFileName, (importFile.arrayBuffer));
            await wasmModule.FS.writeFile(inputFileName, (ab));

            // Create a new document object
            const document = wasmModule.Document.Create();
            // Load the Word file
            document.LoadFromFile(inputFileName);

            // Define output file name
            const outputFileName = "test.docx";

            // Save to PDF
            document.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx });

            // Clean up resources
            document.Dispose();


            // Read the saved file and convert to a Blob object
            const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

            return modifiedFileArray;
            // console.log({htmlStr});

            // outputRef.value.innerHTML=htmlStr;

            // const modifiedFile = new Blob([modifiedFileArray], { type: "text/html" });

            // // Set download properties
            // downloadName.value = outputFileName;
            // downloadUrl.value = URL.createObjectURL(modifiedFile);
        } else {
          console.error("Not Exist wasmModule!:", wasmModule);
        }

    } catch (error) {
        console.error("Error processing the document:", error);
    }

    return null;


};